package com.serookie.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.serookie.entity.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当token失效时和未登录时访问接口时，自定义返回结果
 * @author kevintam
 * @version 1.0
 * @date 2021/3/21 23:24
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint{
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        String message =authException.getMessage();
        System.out.println(message);
        PrintWriter out = response.getWriter();
        Result result = Result.error().message(message);
        if (authException instanceof LockedException) {
            result.setMessage("账户被锁定，请联系管理员!");
        } else if (authException instanceof CredentialsExpiredException) {
            result.setMessage("密码过期，请联系管理员!");
        } else if (authException instanceof AccountExpiredException) {
            result.setMessage("账户过期，请联系管理员!");
        } else if (authException instanceof DisabledException) {
            result.setMessage("账户被禁用，请联系管理员!");
        } else if (authException instanceof BadCredentialsException) {
            result.setMessage("用户名或者密码输入错误，请重新输入!");
        }
        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();
    }
}
